﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace testWX.Data
{
    /// <summary>
    /// 
    /// </summary>
    public class EmployeeProvider : IEmployeeProvider
    {
        /// <summary>
        /// 定义数据类内部的连接字符串存储
        /// </summary>
        private readonly string _connectionString;

        /// <summary>
        /// 接收参数->传递连接字符串
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        public EmployeeProvider(string connectionString)
        {
            _connectionString = connectionString;
        }

        /// <summary>
        /// 返回可枚举的Employee类对象
        /// </summary>
        /// <returns>返回可枚举的Employee类对象</returns>
        public IEnumerable<Employee> Get()
        {
            IEnumerable<Employee> employee;
            using (var connection = new SqlConnection(_connectionString))
            {
                const string query = "select id, first_name as FirstName, last_name as LastName, address, home_phone as HomePhone, cell_phone as CellPhone from employee";
                employee = connection.Query<Employee>(query);
            }
            return employee;
        }

        /// <summary>
        /// 根据参数id，返回一个Employee类对象
        /// </summary>
        /// <param name="id">Employee类对象的的id</param>
        /// <returns>一个Employee类对象</returns>
        public Employee Single(int id)
        {
            Employee employee;
            using (var connection = new SqlConnection(_connectionString))
            {
                const string query = "SELECT id, first_name as FirstName, last_name as LastName, address, home_phone as HomePhone, cell_phone as CellPhone FROM employee WHERE id = @id";
                employee = connection.Query<Employee>(query, new { id }).SingleOrDefault();
            }
            return employee;
        }
    }
}
